// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a'
}) // 使用当前云环境
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  
  try {
    // 验证管理员身份
    const result = await cloud.callFunction({
      name: 'checkAdminAuth',
      data: {
        adminId: event.adminId || '',
        token: event.token || ''
      }
    })
    
    const { code, data } = result.result
    
    if (code !== 0 || !data) {
      return {
        code: 401,
        data: null,
        message: '未授权访问'
      }
    }
    
    // 查询条件
    let condition = {}
    
    // 根据状态筛选
    if (event.status === 'ongoing') {
      condition.status = '借用中'
    } else if (event.status === 'completed') {
      condition.status = '已归还'
    }
    
    // 使用聚合查询获取订单列表（包含装备信息和用户信息）
    const { list } = await db.collection('orders')
      .aggregate()
      .match(condition)
      .lookup({
        from: 'equipment',
        localField: 'equipmentId',
        foreignField: '_id',
        as: 'equipmentList'
      })
      .lookup({
        from: 'users',
        localField: 'userId',
        foreignField: '_id',
        as: 'userList'
      })
      .addFields({
        equipment: $.arrayElemAt(['$equipmentList', 0]),
        userInfo: $.arrayElemAt(['$userList', 0])
      })
      .project({
        equipmentList: 0,
        userList: 0
      })
      .sort({
        borrowTime: -1
      })
      .end()
    
    return {
      code: 0,
      data: list,
      message: '获取订单列表成功'
    }
  } catch (err) {
    return {
      code: 500,
      data: null,
      message: '获取订单列表失败: ' + err.message
    }
  }
} 